package com.solcoo.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.solcoo.dao.RecommendDao;
import com.solcoo.dao.UseromrelaDao;
import com.solcoo.dao.YongHuDao;
import com.solcoo.dao.ZhangHuDao;
import com.solcoo.pojo.Recommend;
import com.solcoo.pojo.Useromrela;
import com.solcoo.pojo.YongHu;
import com.solcoo.util.SendMsgUtil;

@Controller
public class CommonController {

	private static Logger logger = Logger.getLogger(CommonController.class);

	@Resource
	private RecommendDao recommendDao;
	@Resource
	private YongHuDao yongHuDao;
	@Resource
	private ZhangHuDao zhangHuDao;
	@Resource
	private UseromrelaDao useromrelaDao;
	
	@RequestMapping(value="jjhuafeiCallback.jspDo")
	public @ResponseBody String jjhuafeiCallback(Integer result, String out_trade_id,
			String state, String account, Integer product_id, Integer price, String product_info) throws Exception {
		logger.error("CommonController.jjhuafeiCallback====result="+result+";out_trade_id="+out_trade_id+";state="+state+";account="+ account
				+";product_id="+product_id+";price="+price+";product_info="+product_info);
		
		if(result!=null && result==0 && "ok".equals(state)) {
			recommendDao.updateRewardRecommend(Integer.parseInt(out_trade_id));
		}
		return "ok";
	}
	
	@RequestMapping(value="getEnabledRecommend.jspDo")
	public @ResponseBody String getEnabledRecommend() throws Exception {
		Map<String, Date> czjlsjs = new HashMap<String, Date>(); // KEY:个人手机号；VALUE:最近推荐时间
		Map<String, String> czjls = new HashMap<String, String>(); // KEY:个人手机号；VALUE:充值手机号,推荐ID
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Calendar todayC = Calendar.getInstance();
		todayC.add(Calendar.DAY_OF_MONTH, 1);
		String today = formatter.format(todayC.getTime());
		List<Recommend> rs = recommendDao.getRewardRecommend(today);
		if(rs!=null && rs.size()>0) {
			// 里面各种校验，顺序注意，调整顺序会带来bug
			for(Recommend r:rs) {
				String czjl = "";
				// 商户版和子账户版推荐个人才有效
				if(!"2".equals(r.getApptype()) || !("1".equals(r.getRdtype())||"3".equals(r.getRdtype()))) {
					recommendDao.updateRewardRecommend(r.getId().intValue());
					logger.error("RewardTask---------type is not invalid:id=" + r.getId());
					continue;
				}

				// 个人注册时间晚于推荐时间有效
				String gerentele = r.getTelephone();
				YongHu geren = yongHuDao.selectUserByPhone(gerentele);
				if(geren==null) {
					continue;
				}
				if(geren.getZhucesj().compareTo(r.getCreateTime())<=0) {
					recommendDao.updateRewardRecommend(r.getId().intValue());
					logger.error("RewardTask---------time1 is not invalid:id=" + r.getId());
					continue;
				}

				// 获取推荐人
				String recommended = r.getRecommended();
				YongHu recommendYh = yongHuDao.selectUserByYonghum(recommended);
				czjl = recommendYh.getShoujih(); // 充值的手机号
				
				// 商户、子账户推荐则校验是否有效商户
				if("1".equals(r.getRdtype())) {
					if(!"1".equals(recommendYh.getEnabled())) {
						recommendDao.updateRewardRecommend(r.getId().intValue());
						logger.error("RewardTask---------recommended1 is not invalid:id=" + r.getId());
						continue;
					}
				} else if("3".equals(r.getRdtype())) {
					Useromrela ur = useromrelaDao.getEnabledEmployee(recommended);
					if(ur != null) {
						recommended = ur.getOwnerid();
						recommendYh = yongHuDao.selectUserByYonghum(recommended);
						czjl += "-" + recommendYh.getShoujih();
						if(!"1".equals(recommendYh.getEnabled())) {
							recommendDao.updateRewardRecommend(r.getId().intValue());
							logger.error("RewardTask---------recommended2 is not invalid:id=" + r.getId());
							continue;
						}
					} else {
						recommendDao.updateRewardRecommend(r.getId().intValue());
						logger.error("RewardTask---------recommended3 is not invalid:id=" + r.getId());
						continue;
					}
				}

				// 距离个人注册时间最近的为有效推荐
				if(czjlsjs.get(gerentele) == null) {
					czjlsjs.put(gerentele, r.getCreateTime());
				} else {
					if(r.getCreateTime().compareTo(czjlsjs.get(gerentele)) > 0) {
						String sxjl = czjls.get(gerentele);
						if(sxjl!=null && !"".equals(sxjl)) {
							recommendDao.updateRewardRecommend(Integer.parseInt(sxjl.split(",")[1]));
							czjls.remove(gerentele);
						} else {
							logger.error("RewardTask~~~~~kao!has logic bug!");
						}
					} else {
						recommendDao.updateRewardRecommend(r.getId().intValue());
						logger.error("RewardTask---------time2 is not invalid:id=" + r.getId() + "; valid is " + czjls.get(gerentele));
						continue;
					}
				}

				// 必须在有效商户上充值，商户、子账户推荐则必须改该店首次充值且充值金额至少50
				Integer shida = zhangHuDao.queryShidA(Integer.parseInt(geren.getYonghum()));
				if(shida==null || shida<=0) {
					logger.error("RewardTask---------chongzhi is not invalid:id=" + r.getId());
					continue;
				}
				
				if("1".equals(r.getRdtype()) || "3".equals(r.getRdtype())) {
					if(shida!=null && !shida.equals(Integer.parseInt(recommended))) {
						recommendDao.updateRewardRecommend(r.getId().intValue());
						logger.error("RewardTask---------merchant is not invalid:id=" + r.getId());
						continue;
					}
				}

				// 增加有效充值记录
				czjl += "," + r.getId();
				czjls.put(r.getTelephone(), czjl);
			}
			
			if(czjls.size() > 0) {
				String content = "";
				for(String key:czjls.keySet()) {
					String czjl = czjls.get(key);
					String mobile = czjl.split(",")[0];
					
					content += mobile + ";";
				}
				if(!"".equals(content)) {
					return "enabled recommend number:" + czjls.size() + ";telephone:" + content;
				}
			}
		}
		return "no enabled recommend";
	}
	
	@RequestMapping(value="sendDownloadUrl.do")
	public @ResponseBody String sendDownloadUrl(String phone, String valicode, HttpSession session) throws Exception {
		if (valicode == null || "".equals(valicode.trim())) {
			return "NO";
		}
		
		int code = (Integer) session.getAttribute("valicode");
		
		if (code != Integer.parseInt(valicode)) {
			return "NO";
		}
		
		String content = "搜卡，为您省钱的手机APP软件。下载地址：http://42.120.7.37/Solcoo/app/ @";
		
		new SendMsgUtil(phone, content, "2").SendMsg();
		
		return "OK";
	}
}
